package me.zhengjie.modules.serviceprovider.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.utils.StringUtils;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.exception.EntityNotFoundException;
import me.zhengjie.modules.monitor.service.RedisService;
import me.zhengjie.modules.serviceprovider.domain.TServiceproviderInfo;
import me.zhengjie.modules.serviceprovider.domain.TServiceproviderManager;
import me.zhengjie.modules.serviceprovider.domain.TServiceproviderPerson;
import me.zhengjie.modules.serviceprovider.repository.TServiceproviderInfoRepository;
import me.zhengjie.modules.serviceprovider.service.TServiceproviderInfoService;
import me.zhengjie.modules.serviceprovider.service.dto.TServiceproviderInfoDTO;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.service.SmsSerivice;
import me.zhengjie.utils.EncryptUtils;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.serviceprovider.repository.TServiceproviderPersonRepository;
import me.zhengjie.modules.serviceprovider.service.TServiceproviderPersonService;
import me.zhengjie.modules.serviceprovider.service.dto.TServiceproviderPersonDTO;
import me.zhengjie.modules.serviceprovider.service.dto.TServiceproviderPersonQueryCriteria;
import me.zhengjie.modules.serviceprovider.service.mapper.TServiceproviderPersonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

/**
* @author xuyukun
* @date 2019-07-20
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TServiceproviderPersonServiceImpl implements TServiceproviderPersonService {
    @Autowired
    private TServiceproviderInfoRepository tServiceproviderInfoRepository;
    @Autowired
    private TServiceproviderPersonRepository tServiceproviderPersonRepository;
    @Autowired
    private TServiceproviderInfoService tServiceproviderInfoService;
    @Autowired
    private TServiceproviderPersonMapper tServiceproviderPersonMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SmsSerivice smsSerivice;

    @Override
    public Object queryAll(TServiceproviderPersonQueryCriteria criteria, Pageable pageable){
        Page<TServiceproviderPerson> page = tServiceproviderPersonRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(tServiceproviderPersonMapper::toDto));
    }

    @Override
    public Object queryAll(TServiceproviderPersonQueryCriteria criteria){
        return tServiceproviderPersonMapper.toDto(tServiceproviderPersonRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public TServiceproviderPersonDTO findById(Long id) {
        Optional<TServiceproviderPerson> tServiceproviderPerson = tServiceproviderPersonRepository.findById(id);
        ValidationUtil.isNull(tServiceproviderPerson,"TServiceproviderPerson","id",id);
        return tServiceproviderPersonMapper.toDto(tServiceproviderPerson.get());
    }



    @Override
    public TServiceproviderPersonDTO findByPhone(String username) {
        List<TServiceproviderPerson> list = tServiceproviderPersonRepository.findByPhoneAndIsDelete(username,0);  //未删除
        if(list.size() == 0)
            return null ;
        return tServiceproviderPersonMapper.toDto(list.get(0));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TServiceproviderPersonDTO create(TServiceproviderPerson resources) {
        /*List<TServiceproviderPerson> personList = tServiceproviderPersonRepository.findByAccountAndIsDelete(resources.getAccount(),0);
        if(personList.size() > 0){
            throw new BadRequestException("服务商人员账号重复，请重新输入");
        }*/

        List<TServiceproviderPerson> personList = tServiceproviderPersonRepository.findByPhoneAndIsDelete(resources.getPhone(),0);
        if(personList.size() > 0){
            throw new BadRequestException("服务商人员手机号码重复，请重新输入");
        }

        Timestamp date = new Timestamp(System.currentTimeMillis());
        resources.setCreatTime(date);
        resources.setAccount(resources.getPhone());  //账号手机合并
        TServiceproviderInfo tServiceproviderInfoDTO = tServiceproviderInfoRepository.findById(resources.getServiceproviderId()).get();
        if(tServiceproviderInfoDTO!=null){
            resources.setServiceproviderName(tServiceproviderInfoDTO.getSeproName());
        }
        return tServiceproviderPersonMapper.toDto(tServiceproviderPersonRepository.save(resources));
    }

    @Override
    public void batchCreate(List<TServiceproviderPerson> personList) {
        TServiceproviderInfo tServiceproviderInfoDTO = null;
        Timestamp date = new Timestamp(System.currentTimeMillis());

        for(TServiceproviderPerson resources: personList) {
            if(tServiceproviderInfoDTO == null)
                tServiceproviderInfoDTO =  tServiceproviderInfoRepository.findById(resources.getServiceproviderId()).get();

            resources.setServiceproviderName(tServiceproviderInfoDTO.getSeproName());
            resources.setCreatTime(date);
            tServiceproviderPersonRepository.save(resources);
            smsSerivice.sendBatchSms(resources.getPhone(),"","APP");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TServiceproviderPerson resources) {
        Optional<TServiceproviderPerson> optionalTServiceproviderPerson = tServiceproviderPersonRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalTServiceproviderPerson,"TServiceproviderPerson","id",resources.getId());
        TServiceproviderPerson tServiceproviderPerson = optionalTServiceproviderPerson.get();

        resources.setAccount(resources.getPhone());

        if(!resources.getPhone().equals(tServiceproviderPerson.getPhone())){
            List<TServiceproviderPerson> personList = tServiceproviderPersonRepository.findByPhoneAndIsDelete(resources.getPhone(),0);
            if(personList.size()>0 && !personList.get(0).equals(resources.getId())){
                throw new BadRequestException("服务商人员账号重复，请重新输入");
            }
        }
        // 此处需自己修改
        resources.setId(tServiceproviderPerson.getId());
        if(StringUtils.isEmpty(resources.getPersonPassword())){
            resources.setPersonPassword(tServiceproviderPerson.getPersonPassword());
        }

        Timestamp date = new Timestamp(System.currentTimeMillis());
        resources.setCreatTime(date);
        resources.setAccount(resources.getPhone()); //账号不再用
        resources.setIsDelete(0);
        TServiceproviderInfo tServiceproviderInfoDTO=tServiceproviderInfoRepository.findById(resources.getServiceproviderId()).get();
        if(tServiceproviderInfoDTO!=null){
            resources.setServiceproviderName(tServiceproviderInfoDTO.getSeproName());
        }
        tServiceproviderPersonRepository.save(resources);
    }

    @Override
    public Object register(JSONObject resouces) {
        String username = resouces.getString("account");
        String cellphone = resouces.getString("phone");
        String capta = resouces.getString("captcha");
        String name = resouces.getString("personName");
        String inviteCode = resouces.getString("inviteCode");
        String password = resouces.getString("personPassword");

        String major = resouces.getString("major");
        String country = resouces.getString("country");
        String province = resouces.getString("province");
        String city = resouces.getString("city");
        String county = resouces.getString("county");

        String key = "sms_" + cellphone;
        String cache = redisService.getCodeVal(key) ;
        if(cache == null || !cache.equals(capta)) {
            throw new BadRequestException("验证码不一致!");
        }
        redisService.delete(key);

        username = cellphone; //账号不再用
        /*
        List<TServiceproviderPerson> personList = tServiceproviderPersonRepository.findByAccountAndIsDelete(username,0);
        if(personList.size()>0){
            throw new BadRequestException("该账号已存在");
        }*/
        List<TServiceproviderPerson> personList = tServiceproviderPersonRepository.findByPhoneAndIsDelete(cellphone,0);
        if(personList.size()>0) {
            throw new BadRequestException("手机号码已存在");
        }

        TServiceproviderPerson person = new TServiceproviderPerson();
        person.setPersonName(name);
        person.setAccount(username);
        person.setPersonPassword(password);
        person.setPhone(cellphone);
        if(StringUtils.isEmpty(inviteCode)) {
            person.setServiceproviderId(6L);
            person.setServiceproviderName("浙江申龙人力资源服务有限公司");
        }else{
            Optional<TServiceproviderInfo> infoOptional = tServiceproviderInfoRepository.findByInviteCode(inviteCode);
            TServiceproviderInfo info = infoOptional.get();
            person.setServiceproviderId(info.getId());
            person.setServiceproviderName(info.getSeproName());
        }
        person.setCreatTime(new Timestamp(System.currentTimeMillis()));
        person.setIsManager(0); //非管理员
        person.setCountry(country);
        person.setProvince(province);
        person.setCity(city);
        person.setCounty(county);
        person.setMajor(major);
        person.setLevel("初级");
        person.setIsDelete(0);
        return tServiceproviderPersonRepository.save(person);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        Optional<TServiceproviderPerson> personOptional = tServiceproviderPersonRepository.findById(id);
        if(!personOptional.isPresent()) {
            throw new BadRequestException("用户不存在");
        }
        TServiceproviderPerson person = personOptional.get();
        person.setIsDelete(1);

        tServiceproviderPersonRepository.saveAndFlush(person);
        //tServiceproviderPersonRepository.deleteById(id);
    }

    @Override
    public TServiceproviderPersonDTO findByUsername(String username) {
        List<TServiceproviderPerson> personList = tServiceproviderPersonRepository.findByAccountAndIsDelete(username,0);
        if(personList.size()==0)
            return null;
        else
            return tServiceproviderPersonMapper.toDto(personList.get(0));
    }
    /*
    @Override
    public TServiceproviderPersonDTO findByAccount(String username) {
        List<TServiceproviderPerson> list = tServiceproviderPersonRepository.findByAccountAndIsDelete(username,0);  //未删除
        ValidationUtil.isNull(list,"TServiceproviderPerson","account", username);
        return tServiceproviderPersonMapper.toDto(list.get(0));
    }*/

    @Override
    public Object resetpassword(JSONObject resouces) {
        String cellphone = resouces.getString("cellphone");
        String capta = resouces.getString("captcha");
        String password = resouces.getString("password");

        String key = "sms_" + cellphone;
        String cache = redisService.getCodeVal(key) ;
        if(cache == null || !cache.equals(capta)) {
            throw new BadRequestException("验证码不一致!");
        }
        redisService.delete(key);


        List<TServiceproviderPerson> managerList = tServiceproviderPersonRepository.findByPhoneAndIsDelete(cellphone,0);
        if(managerList.size()==0) {
            throw new BadRequestException("账号不存在");
        }

        TServiceproviderPerson person = managerList.get(0);
        person.setPersonPassword(password);
        return tServiceproviderPersonRepository.saveAndFlush(person);
    }

    @Override
    public Object rebind(JSONObject resouces) {
        Long id = resouces.getLong("id"); //用户标识
        Optional<TServiceproviderPerson> optional = tServiceproviderPersonRepository.findById(id);

        String cellphone = resouces.getString("cellphone");
        String capta = resouces.getString("captcha");

        String key = "sms_" + cellphone;
        String cache = redisService.getCodeVal(key) ;
        if(cache == null || !cache.equals(capta)) {
            throw new BadRequestException("验证码不一致!");
        }
        redisService.delete(key);


        List<TServiceproviderPerson> personList = tServiceproviderPersonRepository.findByPhoneAndIsDelete(cellphone,0);
        if(personList.size() > 0 && personList.get(0).getId().longValue() != id) {
            throw new BadRequestException("该手机号码已被使用!");
        }
        TServiceproviderPerson  person = optional.get();
        person.setPhone(cellphone);
        return tServiceproviderPersonRepository.saveAndFlush(person);
    }
}